<template>
	<div>
		<div class="container">
			<a-form ref="searchRef" :model="searchState" @finish="loading=true;initData()">
				<a-row :gutter="20">
					<a-col :span="6">
						<a-form-item label="项目">
							<a-select v-model:value="searchState.project_id" :show-search="true" placeholder="请选择项目" :options="innerProjectOptions" option-filter-prop="label" allow-clear @change="projectChange"></a-select>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="供应商">
							<a-select v-model:value="searchState.supplier_id" :show-search="true" placeholder="请选择供应商" :options="innerSupplierList" option-filter-prop="label" allow-clear :disabled="userInfo.is_supplier === 1"></a-select>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="物资类型">
							<a-select v-model:value="searchState.contract_type" :show-search="true" placeholder="请选择物资类型" :options="materialTypesOptions" option-filter-prop="label" allow-clear></a-select>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="物资名称">
							<a-input v-model:value="searchState.material_name" placeholder="请输入物资名称" allow-clear></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="5">
						<a-form-item label="时间范围">
							<a-range-picker v-model:value="searchState.date_range" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
						</a-form-item>
					</a-col>
					<a-col :span="9">
						<a-radio-group v-model:value="searchState.date_type" style="margin-left: 20px;" @change="setDatetype">
							<a-radio :value="1">本月</a-radio>
							<a-radio :value="2">上月</a-radio>
							<a-radio :value="3">本季</a-radio>
							<a-radio :value="4">上季</a-radio>
							<a-radio :value="5">本年</a-radio>
							<a-radio :value="6">上年</a-radio>
						</a-radio-group>
					</a-col>
					<a-col :span="2">
						<a-form-item>
							<a-space>
								<a-button type="primary" @click="search">
									<search-outlined />搜索
								</a-button>
								<a-button type="primary" @click="handleExport">
									导出
								</a-button>
								<!--								<a-button type="primary" @click="printElement('supply-order-statistics')">-->
								<!--									打印/导出PDF-->
								<!--								</a-button>-->
							</a-space>
						</a-form-item>
					</a-col>
				</a-row>
			</a-form>
			<div id="supply-order-statistics" class="mt-2">
				<h2 class="text-center">{{ title }}</h2>
				<a-table v-if="!loading" :columns="columns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="statisticsList" :pagination="pagination" show-size-changer :loading="loading" @change="initData"></a-table>
			</div>
		</div>
	</div>
</template>
<script setup>
import { SearchOutlined } from "@ant-design/icons-vue";
import { computed, reactive, ref } from "vue";
import { usePagination } from "vue-request";
import { post } from "@/utils/index.js";
import dayjs from "dayjs";
import { printElement } from "@/utils/exportData.js";
import { useRoute, useRouter } from "vue-router";
import { userStore } from "@/store/index.js";
const projectOptions = ref([]);
const userlist = ref([]); // 供应商列表
const materialTypesOptions = ref([
	{
		value: 1,
		label: "主要物资"
	},
	{
		value: 2,
		label: "周转材料"
	},
	{
		value: 3,
		label: "机械"
	},
	{
		value: 4,
		label: "辅助材料"
	},
]);
const columns = [
	{
		title: "ID",
		dataIndex: "id",
		key: "id",
		width: 80,
		align: "left",
		fixed: "left",
		customRender: ({ text, record, index, column }) => {
			return index + 1;
		}
	},
	{
		title: "项目名称",
		dataIndex: "project_name",
		sorter: false,
		ellipsis: true,
		fixed: "left",
	},
	{
		title: "供应商",
		dataIndex: "supplier_name",
		sorter: false,
		ellipsis: true,
		fixed: "left",
	},
	{
		title: "物资名称",
		dataIndex: "material_name",
		sorter: false,
		ellipsis: true,
		fixed: "left",
	},
	{
		title: "规格型号",
		dataIndex: "model",
		sorter: false,
		ellipsis: true,
	},
	{
		title: "计量单位",
		dataIndex: "unit",
		sorter: false,
		ellipsis: true,
	},
	{
		title: "物资类型",
		dataIndex: "contract_type",
		sorter: false,
		width: 100,
		ellipsis: true,
	},
	{
		title: "发货数量",
		dataIndex: "real_quantity",
		sorter: false,
		width: 80,
		ellipsis: true,
	},
	{
		title: "验收数量",
		dataIndex: "ys_quantity",
		sorter: false,
		width: 80,
		ellipsis: true,
	},
];
const route = useRoute();
const router = useRouter();
const query = route.query;
const searchState = reactive({});
const store = userStore();
const userInfo = store.info;
if (userInfo.is_supplier === 1) {
	searchState.supplier_id = userInfo.id;
}

const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 650 }));
const getSupplierList = () => {
	post("/supplyOrder/statistics/suppliers").then((data) => {
		userlist.value = data.map(d => {
			return {
				value: d.id,
				label: d.supplier_name,
				project_ids: d.project_ids,
			};
		});
	});
}

if (!userlist.value.length) {
	getSupplierList()
}

const innerSupplierList = computed(() => {
	if (!searchState.project_id) return userlist.value;
	return userlist.value.filter(d => {
		return d.project_ids.includes(searchState.project_id);
	})
})

const projectChange = () => {
	// if (searchState.project_id) {
	// 	getSupplierList(searchState.project_id)
	// } else {
	// 	getSupplierList();
	// }
}

post("department/projects?type=3").then(({ data }) => {
	projectOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name,
			parseIds: d.parent_ids.split(',').map(item => parseInt(item)),
		};
	});
});
const innerProjectOptions = computed(() => {
	return projectOptions.value;
})
const { data, loading, run, current, pageSize, total } = usePagination(
	params => {
		// if (!searchState.supply_order_ids.length) return;
		const [start_date, end_date] = searchState.date_range || [];
		return post("supplyOrder/statistics", { ...params, ...searchState, start_date, end_date });
	}, {
		pagination: {
			currentKey: "page",
			pageSizeKey: "page_size",
			totalKey: "total"
		}
	});
const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value,
}));
const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = {
		...filters,
		...searchState
	};
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
const setDatetype = () => {
	const quarter = dayjs().set('month', parseInt(dayjs().month() / 3 + '') * 3).startOf('month').format('YYYY-MM-DD');
	switch (searchState.date_type) {
	// 本月
	case 1:
		searchState.date_range = [
			dayjs().startOf("month").format("YYYY-MM-DD"),
			dayjs().endOf("month").format("YYYY-MM-DD")
		];
		break;
		// 上月
	case 2:
		searchState.date_range = [
			dayjs().startOf("month").subtract(1, "month").format("YYYY-MM-DD"),
			dayjs().endOf("month").subtract(1, "month").format("YYYY-MM-DD")
		];
		break;
		// 本季
	case 3:
		searchState.date_range = [quarter, dayjs(quarter).add(2, 'month').endOf('month').format('YYYY-MM-DD')];
		break;
		// 上季
	case 4:
		searchState.date_range = [dayjs(quarter).subtract(3, 'month').format('YYYY-MM-DD'), dayjs(quarter).subtract(1, 'day').format('YYYY-MM-DD')];
		break;
		// 本年
	case 5:
		searchState.date_range = [dayjs().startOf('year').format('YYYY-MM-DD'), dayjs().endOf('year').format('YYYY-MM-DD')];
		break;
		// 上年
	case 6:
		searchState.date_range = [dayjs().subtract(1, 'year').startOf('year').format('YYYY-MM-DD'), dayjs().subtract(1, 'year').endOf('year').format('YYYY-MM-DD')];
		break;
	}
}

const statisticsList = computed(() =>
	(data.value?.data || []).map(d => {
		if (d.children?.length === 0) delete d.children;
		return d;
	})
);

const title = computed(() => {
	const _title = '发货统计表';
	let _prex = '';
	if (searchState.date_range?.length) {
		_prex += `${searchState.date_range[0]}至${searchState.date_range[1]}`;
	}
	if (searchState.project_id) {
		_prex += `${innerProjectOptions.value.find(item => item.value === searchState.project_id)?.label}`;
	}
	if (searchState.contract_type) {
		_prex += `${materialTypesOptions.value.find(item => item.value === searchState.contract_type)?.label}`;
	}
	return _prex + _title;
})
const search = () => {
	const query = {};
	if (searchState.project_id) {
		query['project_id'] = searchState.project_id;
	}
	if (searchState.contract_type) {
		query['contract_type'] = searchState.contract_type;
	}
	if (searchState.date_range?.length) {
		query['start_date'] = searchState.date_range[0];
		query['end_date'] = searchState.date_range[1];
	}
	if (searchState.supplier_id) {
		query['supplier_id'] = searchState.supplier_id;
	}
	if (searchState.material_name) {
		query['material_name'] = searchState.material_name;
	}
	router.replace({ query })
	loading.value = true;
	initData()
}
if (query) {
	if (query.project_id) searchState.project_id = parseInt(query.project_id);
	if (query.contract_type) searchState.contract_type = parseInt(query.contract_type);
	if (query.start_date && query.end_date) searchState.date_range = [query.start_date, query.end_date];
	initData();
}
const handleExport = () => {
	post("supplyOrder/statistics", {
		page_size: Infinity,
		submit: 'export',
		...searchState
	}).then(({ url }) => {
		if (url) {
			window.open(url, '_blank')
		}
	})
}
</script>
<style scoped lang="scss">
.container {
  background: #fff;
  padding: 12px;
}
</style>